package org.simpleProxy;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.luceneEngine.LuceneTxtHandler;
import org.luceneEngine.LuceneDocHandler;
public class FileHandler extends Thread {

	
	static Logger logger = Logger.getLogger(FileHandler.class.getName());
	private LuceneTxtHandler txtHandler;
	private LuceneDocHandler docHandler;
	
	public FileHandler() {
		try {
			txtHandler = new LuceneTxtHandler("luceneIndex");
			docHandler = new LuceneDocHandler("luceneIndex");
		} catch (IOException e) {
			logger.fatal("Could not open the lucene index!");
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		while(true){
			FilenameContainer container = new FilenameContainer();
			try {
				String fileName = container.take();
				logger.info("Got FileName: " + fileName);
				String extension = fileName.split("\\.")[1];
				
				
				//Handle any of the extensions here - we should probably have them all implement one default interface
				// E.g. LuceneTxtHandler implements Lucene handler
				if(extension.equals("txt")){
					logger.info("Got .txt extension - proceeding to handle");
					String[] chunks = fileName.split("[\\\\]");
					txtHandler.writeContents(fileName, chunks[chunks.length-1]);
				}
				//Handle doc or docx extensions
				else if(extension.equals("doc") || extension.equals("docx")){
					logger.info("Got .doc[x] extension - proceeding to handle");
					String[] chunks = fileName.split("[\\\\]");
					logger.debug("Got end: " + chunks[chunks.length-1]);
					docHandler.writeContents(fileName, chunks[chunks.length-1]);
				}
			} catch (InterruptedException e) {
				try {
					wait(2);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					logger.error(e1.getMessage());
					break;
				}
			}
		}
		super.run();
	}
}
